﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_VBPQ_Edit
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

#Region "Sub and Function "
    Protected Sub ShowData()
        Using data As New VSEntities
            Dim p As VBPQDocument = (From q In data.VBPQDocuments Where q.Id = hidID.Value Select q).SingleOrDefault
            If Not p Is Nothing Then
                txtTitle.Text = IIf(IsNothing(p.TrichYeu) = True, "", p.TrichYeu)
                txtCode.Text = IIf(IsNothing(p.SoKyHieu) = True, "", p.SoKyHieu)
                txtContent.Text = IIf(IsNothing(p.NoiDung) = True, "", p.NoiDung)
                drpType.SelectedValue = p.LoaiVanBanId
                'drpStatus.SelectedValue = p.StatusId
                If Not p.NgayBanHanh Is Nothing Then
                    txtPublishedDate.Text = formatDate(p.NgayBanHanh)
                Else
                    txtPublishedDate.Text = ""
                End If
                If Not p.NgayDangCongBao Is Nothing Then
                    txtPrintedDate.Text = formatDate(p.NgayDangCongBao)
                Else
                    txtPrintedDate.Text = ""
                End If
                If Not p.NgayCoHieuLuc Is Nothing Then
                    txtValidatedDate.Text = formatDate(p.NgayCoHieuLuc)
                Else
                    txtValidatedDate.Text = ""
                End If
                If Not p.NgayHetHieuLuc Is Nothing Then
                    txtExpiredDate.Text = formatDate(p.NgayHetHieuLuc)
                Else
                    txtExpiredDate.Text = ""
                End If
                txtPublisher.Text = IIf(IsNothing(p.NguonTrich) = True, "", p.NguonTrich)
                'Show loai van ban
                Dim lvb = (From ck In data.VBPQLoaiVanBans Select ck).ToList
                If Not lvb Is Nothing Then
                    drpType.DataSource = lvb
                    drpType.DataTextField = "LoaiVanBan"
                    drpType.DataValueField = "Id"
                    drpType.DataBind()
                End If
                'Show co quan ban hanh da duoc chon
                Dim cq = (From a In data.VBPQCoQuanBanHanhDocuments Join b In data.VBPQCoQuanBHs On a.CoQuanBanHanh _
                          Equals b.Id Where a.DocumentId = hidID.Value Select b).ToList
                If cq.Count > 0 Then ' Ton tai CQBH duoc chon
                    lsbPromulgator.DataSource = cq
                    lsbPromulgator.DataTextField = "CoQuanBH"
                    lsbPromulgator.DataValueField = "Id"
                    lsbPromulgator.DataBind()
                    'Show co quan ban hanh con lai
                    For j As Integer = 0 To cq.Count - 1
                        Dim cqbh1 As String = cq(j).CoQuanBH.ToString 'CQBH da duoc chon
                        Dim cqbh = (From ck In data.VBPQCoQuanBHs Where Not ck.CoQuanBH.Contains(cqbh1) Select ck).ToList
                        If Not cqbh Is Nothing Then
                            lsbExistingPromulgator.DataSource = cqbh
                            lsbExistingPromulgator.DataTextField = "CoQuanBH"
                            lsbExistingPromulgator.DataValueField = "Id"
                            lsbExistingPromulgator.DataBind()
                        End If
                    Next
                Else ' Khong co CQBH nao da duoc chon
                    ' Hien thu ra tat cac CQBH co trong du lieu
                    Dim cqbh = (From ck In data.VBPQCoQuanBHs Select ck).ToList
                    If Not cqbh Is Nothing Then
                        lsbExistingPromulgator.DataSource = cqbh
                        lsbExistingPromulgator.DataTextField = "CoQuanBH"
                        lsbExistingPromulgator.DataValueField = "Id"
                        lsbExistingPromulgator.DataBind()
                    End If
                End If
                'Show nguoi ky duoc chon                
                Dim nk1 = (From a In data.VBPQChucDanhNguoiKies Join b In data.VBPQNguoiKies On a.NguoiKyId _
                          Equals b.Id Where a.DocumentId = hidID.Value Select b).ToList
                If nk1.Count > 0 Then ' VBPQ nay da co nguoi ky
                    lsbSigner.DataSource = nk1
                    lsbSigner.DataTextField = "NguoiKy"
                    lsbSigner.DataValueField = "Id"
                    lsbSigner.DataBind()
                    'Show nguoi ky con lai      
                    For i As Integer = 0 To nk1.Count - 1
                        Dim nk2 As String = nk1(i).NguoiKy.ToString ' Nguoi ky da ton tai trong VBPQ
                        Dim nk = (From ck In data.VBPQNguoiKies Where Not ck.NguoiKy.Contains(nk2) Select ck).ToList
                        If Not nk Is Nothing Then
                            lsbExistingSigner.DataSource = nk
                            lsbExistingSigner.DataTextField = "NguoiKy"
                            lsbExistingSigner.DataValueField = "Id"
                            lsbExistingSigner.DataBind()
                        End If
                    Next
                Else ' khong co chu ky nao duoc chon. Hien thi ra het tat ca chu ky co trong du lieu
                    Dim nk = (From ck In data.VBPQNguoiKies Select ck).ToList
                    If Not nk Is Nothing Then
                        lsbExistingSigner.DataSource = nk
                        lsbExistingSigner.DataTextField = "NguoiKy"
                        lsbExistingSigner.DataValueField = "Id"
                        lsbExistingSigner.DataBind()
                    End If
                End If

                'Show chuc danh da duoc chon
                Dim cd1 = (From a In data.VBPQChucDanhNguoiKies Join b In data.VBPQChucDanhs On a.ChucDanhId _
                          Equals b.Id Where a.DocumentId = hidID.Value Select b).ToList
                If cd1.Count > 0 Then ' Ton tai chuc danh trong VBPQ
                    lsbOffice.DataSource = cd1
                    lsbOffice.DataTextField = "ChucDanh"
                    lsbOffice.DataValueField = "Id"
                    lsbOffice.DataBind()
                    For i As Integer = 0 To cd1.Count - 1
                        Dim cd2 As String = cd1(i).ChucDanh.ToString ' chuc danh da duoc chon
                        ' Lay ra cac chuc danh con lai khong nam trong chuc danh da duoc chon
                        Dim cd = (From ck In data.VBPQChucDanhs Where Not ck.ChucDanh.Contains(cd2) Select ck).ToList
                        If Not cd Is Nothing Then
                            lsbExistingOffice.DataSource = cd
                            lsbExistingOffice.DataTextField = "ChucDanh"
                            lsbExistingOffice.DataValueField = "Id"
                            lsbExistingOffice.DataBind()
                        End If
                        ' ket thuc hien thi cac chuc danh con lai
                    Next
                Else ' khong co chuc danh nao duoc chon. hien thi ra het tat ca chuc danh co trong du lieu.                    
                    Dim cd = (From ck In data.VBPQChucDanhs Select ck).ToList
                    If Not cd Is Nothing Then
                        lsbExistingOffice.DataSource = cd
                        lsbExistingOffice.DataTextField = "ChucDanh"
                        lsbExistingOffice.DataValueField = "Id"
                        lsbExistingOffice.DataBind()
                    End If
                End If
            End If
        End Using
    End Sub
    Public Sub Move(ByVal SourceList As ListBox, ByVal DestList As ListBox)
        Dim lstSelected = SourceList.GetSelectedIndices()
        Dim i As Integer = lstSelected.Count
        Dim size As Integer = SourceList.Items.Count()
        While i > 0
            i = i - 1
            Dim Indexed As Integer = lstSelected(i)
            DestList.Items.Add(SourceList.Items(Indexed))
            SourceList.Items.RemoveAt(Indexed)

        End While
        SourceList.SelectedValue = Nothing
        DestList.SelectedValue = Nothing
    End Sub
#End Region
#Region "Event for control"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If

            If Not Request.QueryString("Id").ToString.Equals("0") Then
                hidID.Value = Request.QueryString("Id")
                ShowData()
            End If
        End If
    End Sub
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            Dim p As VBPQDocument = (From q In data.VBPQDocuments Where q.Id = hidID.Value).SingleOrDefault
            Try
                p.TrichYeu = txtTitle.Text.Trim()
                p.SoKyHieu = txtCode.Text.Trim()
                p.LoaiVanBanId = drpType.SelectedValue
                p.NgayBanHanh = IIf(String.IsNullOrEmpty(txtPublishedDate.Text.ToString), Nothing, StringToDate(txtPublishedDate.Text.Trim()))
                p.NgayDangCongBao = IIf(String.IsNullOrEmpty(txtPrintedDate.Text.ToString), Nothing, StringToDate(txtPrintedDate.Text.Trim()))
                p.NgayCoHieuLuc = IIf(String.IsNullOrEmpty(txtValidatedDate.Text.ToString), Nothing, StringToDate(txtValidatedDate.Text.Trim()))
                p.NgayHetHieuLuc = IIf(String.IsNullOrEmpty(txtExpiredDate.Text.ToString), Nothing, StringToDate(txtExpiredDate.Text.Trim()))
                p.NguonTrich = txtPublisher.Text.Trim()
                p.NoiDung = txtContent.Text.Trim()
                ' Delete bang VBPQCoQuanBanHanhDocument
                Dim obj = (From ck In data.VBPQCoQuanBanHanhDocuments Where ck.DocumentId = p.Id Select ck).ToList
                For Each x In obj
                    data.VBPQCoQuanBanHanhDocuments.DeleteObject(x)
                Next
                data.SaveChanges()
                'Insert lai vao bang VBPQCoQuanBanHanhDocument              
                For i As Integer = 0 To lsbPromulgator.Items.Count - 1
                    Dim cqbh As New VBPQCoQuanBanHanhDocument
                    cqbh.DocumentId = p.Id
                    cqbh.CoQuanBanHanh = lsbPromulgator.Items(i).Value
                    data.VBPQCoQuanBanHanhDocuments.AddObject(cqbh)
                Next
                data.SaveChanges()
                ' Delete bang VBPQChucDanhNguoiKy
                Dim c = (From ck In data.VBPQChucDanhNguoiKies Where ck.DocumentId = p.Id Select ck).ToList
                For Each x In c
                    data.VBPQChucDanhNguoiKies.DeleteObject(x)
                Next
                data.SaveChanges()
                ' Luu vao bang VBPQChucDanhNguoiKy
                ' Luu vao bang VBPQChucDanhNguoiKy
                If lsbSigner.Items.Count = lsbOffice.Items.Count Then 'so luong nguoi ky duoc chon bang voi so luong chuc danh
                    For i As Integer = 0 To lsbSigner.Items.Count - 1
                        For j As Integer = i To lsbOffice.Items.Count - 1
                            Dim nk As New VBPQChucDanhNguoiKy
                            nk.DocumentId = p.Id
                            nk.NguoiKyId = lsbSigner.Items(i).Value
                            nk.ChucDanhId = lsbOffice.Items(j).Value
                            data.VBPQChucDanhNguoiKies.AddObject(nk)
                            Exit For
                        Next
                    Next
                ElseIf lsbSigner.Items.Count < lsbOffice.Items.Count Then 'so luong nguoi ky duoc chon it hon so luong chuc danh
                    For i As Integer = 0 To lsbSigner.Items.Count - 1
                        For j As Integer = 0 To lsbOffice.Items.Count - 1
                            Dim nk As New VBPQChucDanhNguoiKy
                            nk.DocumentId = p.Id
                            nk.NguoiKyId = lsbSigner.Items(i).Value
                            nk.ChucDanhId = lsbOffice.Items(j).Value
                            data.VBPQChucDanhNguoiKies.AddObject(nk)
                        Next
                    Next
                End If
                data.SaveChanges()
                'Insert_App_Log("Insert Candidate:" & txtTitle.Text.Trim & "", Function_Name.Candidate, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/VBPQ/List.aspx';", Me.Page, True)
            Catch ex As Exception
                '        log4net.Config.XmlConfigurator.Configure()
                '        log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                '        Excute_Javascript("Alertbox('Cập nhật thất bại.');", Me.Page, True)
            End Try
        End Using
    End Sub
    Protected Sub btnMoveCQBH_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveCQBH.Click
        Move(lsbExistingPromulgator, lsbPromulgator)
    End Sub
    Protected Sub btnMoveBackCQBH_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveBackCQBH.Click
        Move(lsbPromulgator, lsbExistingPromulgator)
    End Sub
    Protected Sub btnMoveSigner_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveSigner.Click
        Move(lsbExistingSigner, lsbSigner)
    End Sub
    Protected Sub btnMoveBackSigner_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveBackSigner.Click
        Move(lsbSigner, lsbExistingSigner)
    End Sub
    Protected Sub btnMoveOffice_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveOffice.Click
        Move(lsbExistingOffice, lsbOffice)
    End Sub
    Protected Sub btnMoveBackOffice_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMoveBackOffice.Click
        Move(lsbOffice, lsbExistingOffice)
    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx?Id=" & Request("Id"))
    End Sub
    Protected Sub hplInsertSigner_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplInsertSigner.Init
        hplInsertSigner.CssClass = "thickbox"
        hplInsertSigner.NavigateUrl = "~/Page/VBPQSigner/List.aspx?keepThis=true&TB_iframe=true&height=450&width=400&modal=true"
    End Sub
    Protected Sub hplInsertOffice_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplInsertOffice.Init
        hplInsertOffice.CssClass = "thickbox"
        hplInsertOffice.NavigateUrl = "~/Page/VBPQOffice/List.aspx?keepThis=true&TB_iframe=true&height=450&width=400&modal=true"
    End Sub
    Protected Sub hplTypeInsert_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplTypeInsert.Init
        hplTypeInsert.CssClass = "thickbox"
        hplTypeInsert.NavigateUrl = "~/Page/VBPQType/List.aspx?keepThis=true&TB_iframe=true&height=450&width=400&modal=true"
    End Sub
    Protected Sub hplInsertCQBH_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplInsertCQBH.Init
        hplInsertCQBH.CssClass = "thickbox"
        hplInsertCQBH.NavigateUrl = "~/Page/VBPQPromulgator/List.aspx?keepThis=true&TB_iframe=true&height=450&width=400&modal=true"
    End Sub
#End Region
End Class
